package com.king.first.app.windows;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SessionWindowTimeGapExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.Arrays;

public class Session_Windows {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> socketTextStream = env.socketTextStream("hadoop01", 9999);

        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMapStream = socketTextStream.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] s1 = s.split(" ");
                Arrays.stream(s1).forEach(word -> collector.collect(Tuple2.of(word, 1)));
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> keyedStream = flatMapStream.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> tuple2) throws Exception {
                return tuple2.f0;
            }
        });

        // 我们提取了数据元素的第一个字段，用它的长度乘以 1000 作为会话超时的间隔。
        keyedStream.window(ProcessingTimeSessionWindows.withDynamicGap(
                new SessionWindowTimeGapExtractor<Tuple2<String, Integer>>() {
                    @Override
                    public long extract(Tuple2<String, Integer> element) {
                        return element.f1 * 1000L;
                    }
                }
        ));

        keyedStream.window(EventTimeSessionWindows.withGap(Time.seconds(10)));

        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> windowedStream =
                keyedStream.window(ProcessingTimeSessionWindows.withGap(Time.seconds(4)));

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = windowedStream.sum(1);
        sum.print();

        env.execute();
    }
}
